#!/usr/bin/perl

use strict;
use warnings;

use EBox::Global;
use EBox::Asterisk::Extensions;

EBox::init();

my $extensions = new EBox::Asterisk::Extensions;

sub update
{
    my $ldap = $extensions->{ldap};
    $ldap->connection();

    my $edn = $extensions->extensionsDn;
    if (not $ldap->existsDN($edn)) {
        $ldap->add($edn, {attr => [
            'ou' => 'Extensions',
            'objectClass' => 'top',
            'objectClass' => 'organizationalUnit'
           ]});
    } else {
        warn "Extension element $edn already exists";
    }

    my $qdn = $extensions->queuesDn;
    if (not $ldap->existsDN($qdn)) {
        $ldap->add($qdn, { attr => [
            'ou' => 'Queues',
            'objectClass' => 'top',
            'objectClass' => 'organizationalUnit'
           ]});
    } else {
        warn "Queue element $edn already exists";
    }
}

sub clean
{
    $extensions->{ldap}->connection();
    my $ldap = $extensions->{ldap}->{ldap};
    my $edn = $extensions->extensionsDn;
    my $qdn = $extensions->queuesDn;

    my @extns = $extensions->extensions;
        foreach (@extns) {
            $extensions->delExtension($_);
        }

    my $result;
     $result = $ldap->delete($edn);
    ($result->is_error) and warn "Can't remove Extensions leaf ".$result->error;

    $result = $ldap->delete($qdn);
    ($result->is_error) and warn "Can't remove Queues leaf ".$result->error;
}

sub usage
{
    print "Usage: $0 update | clean\n";
    exit 1;
}

unless ($#ARGV == 0) {
    usage();
}

if ($ARGV[0] eq 'update') {
    update();
} elsif ($ARGV[0] eq 'clean') {
    clean();
} else {
    usage();
}

1;
